package queue;

import zhan.Stack;

import java.util.Iterator;

public class Queue<T> implements Iterable<T> {
    //记录首节点
    private Node head;
    //元素个数
    private int N;
    //记录尾结点
    private Node last;

    public Queue(){
        head=new Node (null,null);
        last=null;
        N=0;
    }
    //为空
    boolean isEnpty(){
        return N==0;
        //return head.next==null;
    }

    //插入元素
    public void insert(T t){
        if (isEnpty()) {
            Node newNode = new Node(t, null);
            head.next = newNode;
            //尾结点指向新节点
            last = newNode;

        }else {
            Node newNode=new Node(t,null);
            last.next=newNode;
            last=newNode;
        }
        N++;
    }

    //删除并返回
    public T remove(){
        if (isEnpty()) {
            return null;
        }
        Node n=head.next;
        head.next=n.next;
        N--;
        if (isEnpty()) {
            last = null;
        }
        return (T) n.item;


    }

    @Override
    public Iterator<T> iterator() {
        return new QIterable();
    }

    private class QIterable implements Iterator<T> {
        private Node node=head;
        @Override
        public boolean hasNext() {
            return node.next!=null;
        }


        @Override
        public T next(){
            node=node.next;
            return (T) node.item;
        }
    }
}
